import React from 'react'
import { Table,Icon,Modal,Popconfirm,Message,Form,Row,Select,Col,Button,Input,DatePicker} from 'antd';
const FormItem = Form.Item;
import api from '../../../api/balancelogadvertising';
import PanelBox from '../../../components/PanelBox';
import GateForm from '../../Form/HardGate';
const { RangePicker } = DatePicker;
import moment from 'moment';

export default class TablePage extends React.Component {
  columns = [{
    title: '机构名称',
    key: 'officeName',
    dataIndex: 'officeName',
    width: '13%',
  },{
    title: '金额(单位/元)',
    key: 'money',
    dataIndex: 'money',
    width: '13%',
  }, {
    title: '类型',
    dataIndex: 'type',
    width: '13%',
    render:(text, record, index) =>  {
      switch(record.type){
        case 100:
          return '充值';
        case 101:
          return '提现';
        case 102:
          return '发布广告机广告扣除 ';
        case 103:
          return '发布家庭锁广告扣除';
        case 104:
          return '发布手机屏保广告扣除';
        case 105:
          return '广告机广告获得';
        case 106:
          return '家庭锁广告获得';
        case 107:
          return '手机屏保广告获得';
        default:
          return '未知';
      }
    },
  },{
    title: '创建者',
    key: 'userName',
    dataIndex: 'userName',
    width: '13%',
  },{
    title: '创建时间',
    key: 'createDate',
    dataIndex: 'createDate',
    width: '14%',
  }, {
    title: '操作',
    key: 'id',
    dataIndex: 'id',
    render: (text, record) => (
      <span>
        {/* <a href="javascript:void(0)"  onClick={this.startUpdateUser.bind(this,record)} >编辑</a>
        <span className="ant-divider" /> */}
        <Popconfirm title="您是否要删除该明细?" onConfirm={this.delete.bind(this,record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
      </span>
    ),
  }];

  state = { 
    data: [],
    listtype: [],
    child:[],
    pagination: {},
    loading: false,
    isOpenCreateUser: false,
    isOpenEditUser: false,
    offices:null,
    area:null,
    defaultName:null,
    defaultTime:[]
  };
  handleTableChange = (pagination, filters, sorter) => {
    const pager = this.state.pagination;
    if(pagination.size==1){
      pager.current = pagination.current!=null?pagination.current:pagination.pageNum-1;
    }else{
      pager.current = pagination.current!=null?pagination.current:pagination.pageNum;
    }
    this.setState({
      pagination: pager,
    });
    this.fetch({
      pageSize: pagination.pageSize,  //每页现实条数
      pageNum: pagination.current,  //当前页数
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters, 
    });
  }

   rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      //console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      this.setState({
        delIds: `${selectedRowKeys}`,
      });
    },
    getCheckboxProps: record => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
    }),
  };


  

  fetch = (params = {}) => {
    this.setState({ loading: true });

    if(params.name!=undefined){
      this.setState({
        defaultName:params.name,
      })
    }else{
      this.setState({
        defaultName:this.state.defaultName,
      });
      params.name=this.state.defaultName;
    }
    if(params.startCreateDate!=undefined || params.endCreateDate!=undefined){
      this.setState({
        defaultTime:[moment(params.startCreateDate, "YYYY/MM/DD"), moment(params.endCreateDate, "YYYY/MM/DD")],
      })
    }else{
      this.setState({
        defaultTime:this.state.defaultTime,
      });
      params.startCreateDate=this.state.defaultTime[0];
      params.endCreateDate=this.state.defaultTime[1];
    }
    api.get('/queryAll', {   //分业查询所有
      ...params,
      responseType: 'json'
    }).then((data) => {
      data = data.data;
      const pagination = data;
      pagination.total = data.pages*data.pageSize;
      this.setState({
        loading: false,
        data: data.list,
        pagination,
      });
    });
  } 
  

   componentDidMount = () =>{
    this.fetch({
      pageSize: 20,
      pageNum: 1,
    });
  }

  startCreateUser_default = () =>{
    if (this.resetFields) this.resetFields();
    this.setState({
      isOpenCreateUser: true,
    });
  }
  
  closeCreateUser = () =>{
    this.setState({
      isOpenCreateUser: false,
    });
  }
  closeaddDict = () =>{
    this.setState({
      isOpenCreateUser: false,
    });
    this.handleTableChange(this.state.pagination,{},{});
  }
  startUpdateUser = (record) =>{
    if (this.resetFields) this.resetFields();
      this.setState({
        isOpenEditUser: true,
        hardinfo:record,
      });
  }
  closeUpdateUser = () =>{
    this.setState({
      isOpenEditUser: false,
    });
  }
  closeupdateDict = () =>{
    this.setState({
      isOpenEditUser: false,
    });
    this.handleTableChange(this.state.pagination,{},{});
  }


  //单个删除
  delete = (id,event) => {
    this.deleteHard(id);
  }


  //多删除
  deleteAll = () => {
    const ids = this.state.delIds;
    if(ids == '' || ids == null){
      Message.error('请选择你要删除的数据！');
      return;
    }
    this.deleteHard(ids);
   }


   deleteHard = (ids) => {
    api.delete('/deleteBalancelog', {ids:ids}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('删除成功！');
      this.handleTableChange(this.state.pagination,{},{});
     }else{
      Message.error(result.message);
     }
    });
  }

  // 接收子组件传入的数据及其方法
  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }


  render() {
    let _this = this;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
    class CustomizedForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {   //提交后得到from表单中得值
          if (!err) {
            let params = this.props.form.getFieldsValue().search;
             if(params.date.length>0){
              params.startCreateDate=moment(params.date[0]).format("YYYY-MM-DD");
              params.endCreateDate=moment(params.date[1]).format("YYYY-MM-DD");
             }
             params.pageSize=20;
             params.pageNum=1;
             _this.fetch(params);
          }
        });
        return false;
      }

      render() {
        const { getFieldDecorator} = this.props.form;
        const search = {
          name: "name",
          date: "date",
        };
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          <FormItem {...formItemLayout} label="机构名称" style={{marginRight:'-25px'}}>
            {getFieldDecorator('search.name', {
              initialValue:_this.state.defaultName ? _this.state.defaultName: ''
            })(
              <Input type="text" placeholder="请输入机构名称"/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="添加日期" style={{marginRight:'-20px'}}>
            {getFieldDecorator('search.date', {
                initialValue:_this.state.defaultTime.length>0?_this.state.defaultTime:''
            })(
              <RangePicker format="YYYY/MM/DD" />
            )}
          </FormItem>
          <FormItem style={{marginRight:'10px'}}>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem>
          <FormItem>
            <Popconfirm type="primary" icon="minus" title="您是否要删除选中的所有明细?" onConfirm={_this.deleteAll} okText="是" cancelText="否">
              <Button type="primary" icon="minus" style={{ height: 32,backgroundColor:"gray",border:"gray" }}>删除所选</Button>
            </Popconfirm>
         </FormItem>
        </Form>
      }
    }
    const CusForm = Form.create({})(CustomizedForm);

    return (
      <div>
        <CusForm/>
        <PanelBox>
          <Table columns={this.columns}
            rowKey={record => record.id}
            dataSource={this.state.data}
            pagination={this.state.pagination}
            loading={this.state.loading}
            onChange={this.handleTableChange}
            expandedRowRender={record => <p style={{ margin: 0 }}>　　　备注:{record.remarks}</p>}
            rowSelection={this.rowSelection}
          />
        </PanelBox>
      </div>
    );
  }
}
